﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using Microsoft.Xna.Framework;

namespace XNAGameFeatures.Features
{
    /// <summary>
    /// 
    /// </summary>
    public static class MouseCustomisation
    {
        private static Cursor LoadCustomCursor(string path)
        {
            IntPtr hCurs = LoadCursorFromFile(path);
            if (hCurs == IntPtr.Zero) throw new Win32Exception();
            var curs = new Cursor(hCurs);
            // Note: force the cursor to own the handle so it gets released properly
            var fi = typeof(Cursor).GetField("ownHandle", BindingFlags.NonPublic | BindingFlags.Instance);
            fi.SetValue(curs, true);
            //Marshal.Release(hCurs);
            return curs;
        }

        [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        private static extern IntPtr LoadCursorFromFile(string path);

        /// <summary>
        /// Loads the custom cursor.
        /// </summary>
        public static void LoadCustomCursor(Game game, String path = @"Content\Cursor.cur")
        {
            try
            {
                Cursor cursor = LoadCustomCursor(path);

                Form win = (Form)Control.FromHandle(game.Window.Handle);
                win.Cursor = cursor;
            }
            catch
            {
            }
        }
    }
}
